/**
 * 
 */

$(function(){
	var _h = $(window).height();
	var _w = $(window).width();
	$('#map_div').height(_h - 62);
	/*initLayuiBar(_h);*/
	
	initMap('map_div');
	map.addControl(new OpenLayers.Control.Navigation());
	map.setCenter(new OpenLayers.LonLat(119.52302551269531, 25.963125228881836), 3);
	var basePath = getQueryString('basePath');
	var regionMap = getDistricts(basePath);
	
	var ents;
	var markersLayer;
	var features = [];
	var strategy;
	var clusters;
	var vectorLayer;
	var drawFeatureControls;
	$('#nav_toolbar').show();
	var rtindex = layer.open({
		type: 1,
		title: false,
		shade: 0,
		area: ['480px', '60px'],
		closeBtn: 0,
		offset: ['61px', (_w-480) + 'px'],
		content: $('#nav_toolbar')
	});
	var element = layui.element;
	element.on('nav(nav_tb)', function(elem){
		if(elem.attr('id') == 'nav1') {
			deactivateControls(drawFeatureControls);
			clearWithoutBaseLayers(map);
			makeClusters(basePath, ents, features, strategy, clusters, regionMap);
		} else if(elem.attr('id') == 'nav2') {
			makeDrawControl(map, drawFeatureControls, vectorLayer, '画面');
		}  else if(elem.attr('id') == 'nav3') {
			makeDrawControl(map, drawFeatureControls, vectorLayer, '画圆');
		}   else if(elem.attr('id') == 'nav4') {
			var settings = {
				"async" : true,
				"dataType": 'jsonp',
				"crossDomain" : true,
				"url" : "http://www.fjmap.net/fjmapsvc/api/route?origX=119.56071038408&origY=25.8603488220749&destX=119.624682670157&destY=25.9602942268015&style=&mid=",
				"method" : "GET"
			}

			$.ajax(settings).done(function(data) {
				var result = data[0].result;
				console.log(result);
			});
		} 
	});
});

function makeDrawControl(map, drawFeatureControls, vectorLayer, type) {
	deactivateControls(drawFeatureControls);
	clearWithoutBaseLayers(map);
	var stylemap = new Geo.StyleMap({
		'default': new Geo.Style({
			pointRadius: 2,
			fillColor: "#ee0000",
			fillOpacity: 0.7,
			strokeColor: "#ee0000",
			strokeWidth: 1,
			strokeOpacity: 1
		})
	});
	vectorLayer = new Geo.View2D.Layer.Vector("Vector Layer",{styleMap: stylemap});
	map.addLayers([vectorLayer]);
	//定义绘制控件
	drawFeatureControls = {
		画点:new Geo.View2D.Control.DrawFeature(vectorLayer,Geo.View2D.Handler.Point),
		画线:new Geo.View2D.Control.DrawFeature(vectorLayer,Geo.View2D.Handler.Path),
		画面:new Geo.View2D.Control.DrawFeature(vectorLayer,Geo.View2D.Handler.Polygon,{
			featureAdded: function(feature){
				//监听featureadded事件，当添加要素时会触发此事件
//				console.log(feature.geometry);
				drawFeatureControls['画面'].deactivate();
			}}),
		画圆:new OpenLayers.Control.DrawFeature(vectorLayer, OpenLayers.Handler.RegularPolygon,{
			handlerOptions:{
				sides: 50,
				irregular: true
			},
			featureAdded: function(feature){
				drawFeatureControls['画圆'].deactivate();
			}
		}),
		编辑:new Geo.View2D.Control.ModifyFeature(vectorLayer)
	};
	//添加控件到地图中
	for(var key in drawFeatureControls){
		map.addControl(drawFeatureControls[key]);
	}
	toggleControl(type, drawFeatureControls);
}

//处理点击选中的控件
function toggleControl(value, drawFeatureControls){
	for(var key in drawFeatureControls){
		var control = drawFeatureControls[key];
		if(key == value){
			control.activate();
		}else{
			control.deactivate();
		}
	}
}
function makeClusters(basePath, ents, features, strategy, clusters, regionMap) {
	ents = '';
	features = [];
	strategy = '';
	clusters = ''; 
	$.get(basePath + 'resources/scripts/gis/enterprise_data.json', function(data) {
		ents = data.data;
		// markersLayer = makePoints(basePath, map, markersLayer, ents);
		for (var i = 0; i < ents.length; i++) {
			var ent = ents[i];
			var area = ent.AREA.substring(0, 9);
			if (regionMap[area].hasOwnProperty('count')) {
				regionMap[area].count++;
			} else {
				regionMap[area].count = 1;
			}
			// 
			var point = new OpenLayers.Geometry.Point(ent.LONGITUDE,
					ent.LATITUDE);
			var geometry = point.clone();
			var pointFeature = new OpenLayers.Feature.Vector(geometry);
			pointFeature.attributes = {
				ent_info : ent
			};
			features.push(pointFeature);
		}// for end
		var style = new OpenLayers.Style({
			pointRadius : "${radius}",
			fillColor : "#ff0000",
			fillOpacity : 1,
			strokeColor : "#cc6633",
			// strokeWidth: "${width}",
			strokeOpacity : 0.8,
			fontSize: "12px",
			fontWeight: "bold",
	//		fontColor: "#ffffff",
			label : "${current_count}",
			externalGraphic: "${externalGraphic}",
			graphicWidth: "${graphicWidth}",
			graphicHeight: "${graphicHeight}"
		}, {
			context : {
				width : function(feature) {
					return (feature.cluster) ? 2 : 1;
				},
				radius : function(feature) {
					var pix = 2;
					if (feature.cluster) {
						pix = Math.min(feature.attributes.count, 7) + 15;
					}
					return pix;
				},
				current_count : function(feature) {
					var count;
					if (feature.attributes.count > 1) {
						count = feature.attributes.count;
					} else {
						count = '';
						// feature.cluster[0].attributes.ent_info.ENTERPRISE_NAME;
					}
					return count;
				},
				externalGraphic: function(feature) {
					if (feature.attributes.count > 1) {
						return basePath + 'resources/images/gis/ent_big.png';
					}
					return basePath + 'resources/images/gis/ent_small.png';
				},
				graphicWidth: function(feature) {
					return (feature.attributes.count > 1) ? 32 : 16;
				},
				graphicHeight: function(feature) {
					return (feature.attributes.count > 1) ? 32 : 16;
				}
			}
		});
	
		strategy = new OpenLayers.Strategy.Cluster();
	
		clusters = new OpenLayers.Layer.Vector("Clusters", {
			strategies : [ strategy ],
			styleMap : new OpenLayers.StyleMap({
				"default" : style,
				"select" : {
					fillColor : "#8aeeef",
					strokeColor : "#32a8a9"
				}
			})
		});
	
		map.addLayer(clusters);
	
		var distance;
		var threshold;
		strategy.distance = distance || strategy.distance;
		strategy.threshold = threshold || strategy.threshold || "null";
	
		clusters.addFeatures(features);
		
		
	
	//	var selectVectors = new OpenLayers.Layer.Vector("select", {
	//		styleMap : new OpenLayers.StyleMap({
	//			"default" : {
	//				fillColor : "#00ffff",
	//				strokeColor : "#00ffff",
	//				pointRadius : "2"
	//			}
	//		})
	//	});
	//	map.addLayer(selectVectors);
		var select = new OpenLayers.Control.SelectFeature(clusters, {
			clickout : true,
			toggle : false,
			multiple : false,
			hover : false,
			toggleKey : "ctrlKey", // ctrl key removes from selection
			multipleKey : "shiftKey", // shift key adds to selection
			box : false
		});
		map.addControl(select);
		select.activate();
		clusters.events.on({
			'featureselected' : function(feature) {
				var cluster = feature.feature.cluster;
				if (cluster.length == 1) {
					// 弹窗显示信息
					showInfo(basePath, cluster[0].attributes.ent_info);
				} else {
					var realpoints = new Array(); 
					var sum_x = 0, sum_y = 0;
					for(var i=0; i<cluster.length; i++) {
						var point = cluster[i];
						var geometry = point.geometry;
						var xystr = geometry.x + "-" + geometry.y;
						if($.inArray(xystr, realpoints) == -1) {
							sum_x += geometry.x;
							sum_y += geometry.y;
							realpoints.push(xystr);
						}
					}
					if(realpoints.length > 1) {
						//放大地图
						var cur_zoom = map.getZoom();
						if(cur_zoom <= 3) {
							cur_zoom += 3;
						} else if (cur_zoom <= 6) {
							cur_zoom += 2;
						} else {
							cur_zoom += 1;
						} 
						map.setCenter(new OpenLayers.LonLat(Number(sum_x) / realpoints.length, Number(sum_y) / realpoints.length), cur_zoom);
					} else {
						$('#ent_list').html('');
						var _content = '';
						for(var i=0; i<cluster.length; i++) {
							var point = cluster[i];
							var ent = point.attributes.ent_info;
							var _html = '<li>'
											+ '<a href="javascript:void(0);" class="fly-avatar">'
											+ '<img src="' + basePath + 'resources/images/gis/ent_small.png" alt="' + ent.ENTERPRISE_NAME + '">'
											+ '</a>'
											+ '<h3>'
											+ '<a class="layui-badge">' + getBizLink(ent.BIZ_TYPE, ent.LINK).bizTypes.toString() + '</a>' 
											+ '</h3>'
											+ '<h2>'
											+ '<a href="javascript:void(0);">' + ent.ENTERPRISE_NAME + '</a>'
											+ '</h2>'
											+ '<div class="fly-list-info">'
											+ '<span> ' + ent.LONGITUDE + ',' + ent.LATITUDE + ' </span>'
											+ '</div>'
											+ '<div class="fly-list-info">'
											+ '<span>' + ent.REGISTERED_ADDRESS + '</span>'
											+ '</div>'
										+ '</li>';
							_content += _html;
						}
						$('#ent_list').html(_content);
						layer.open({
							type: 1,
							shade: 0,
							offset: ['65px', '5px'],
							content: $('#hidden_div'),
							cancel : function(index, layero) {
								$('#hidden_div').hide();
	//							console.log(feature);
								//select.unselect(feature);
								select.unselectAll();
								layer.close(index);
							}
						});
						$('#hidden_div').show();
					}
				}
				
			}
		});
	});
}

/*function initLayuiBar(height) {
	var util = layui.util;
	// 执行
	util.fixbar({
		css: {right: 5, bottom: height - 105},
		bar1: '&#xe68e;'
		,click: function(type){
			if(type == 'bar1') {
				//框选
			}
		}
	});
}*/
function showInfo(basePath, info) {
	var layer = layui.layer;
	var html = '<dl>' 
				+ '<dt style="display:inline">公司：</dt>'
				+ '<dd style="display:inline">' + info.ENTERPRISE_NAME + '</dd>' 
				+ '<br/>'
				+ '<dt style="display:inline">地址：</dt>'
				+ '<dd style="display:inline">' + info.ADDRESS + '</dd>'
			+ '</dl>';
	layer.open({
		type: 1,
		closeBtn: 1,
		shadeClose: true,
		title: info.ENTERPRISE_NAME + "信息",
		content: html
	});
}

function makePoints(basePath, map, markersLayer, ents){
	markersLayer = new Geo.View2D.Layer.Markers("Markers");
	map.addLayer(markersLayer);
	var size = new Geo.Size(19,25);
	var offset = new Geo.Pixel(-(size.w/2), -size.h);
	for(var i=0; i<= ents.length - 1; i++) {
		var _obj = ents[i];
		if(_obj.LATITUDE && _obj.LONGITUDE && _obj.LATITUDE != '' && _obj.LONGITUDE != '') {
			var url = basePath + 'resources/images/gis/ent.png';
			var icon = new Geo.View2D.Icon(url, size, offset);
			var geoMarker = new Geo.GeoMarker(new Geo.LonLat(_obj.LATITUDE, _obj.LONGITUDE),icon);
			markersLayer.addMarker(geoMarker);
			geoMarker.setAnimation(Geo.GeoMarker.ANIMATION_BOUNCE, 20, 500);//单次跳动是Geo.GeoMarker.ANIMATION_DROP
		} 
	}
	return markersLayer;
}

function getQueryString(name){
	var scripts = document.getElementsByTagName("script"), 
					src = scripts[scripts.length - 1].src,
					queryStr = src.substring(src.indexOf("?")+1);
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"),
	   			r = queryStr.match(reg);
	if(r!=null) 
		return  unescape(r[2]); 
	return null;
}

function getDistricts(basePath){
	var rs = {};
	$.ajax({
		url: basePath + 'resources/scripts/gis/region_data.json',
		type: 'GET',
		dataType: 'json',
		async: false,
		success: function(data) {
			var _data = data.data[0];
			rs[_data.AREA] = {
					NAME:_data.NAME,
					LON:_data.LON,
					LAT:_data.LAT,
					GBCODE:_data.GBCODE,
					AREA:_data.AREA
			}
			for(var i=0; i<_data.SubDistricts.length; i++){
				rs[_data.SubDistricts[i].AREA] = {
						NAME:_data.SubDistricts[i].NAME,
						LON:_data.SubDistricts[i].LON,
						LAT:_data.SubDistricts[i].LAT,
						GBCODE:_data.SubDistricts[i].GBCODE,
						AREA:_data.SubDistricts[i].AREA
				}
			}
		}
	});
	return rs;
} 